﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace DragDraw.Service
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    public class UploadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            Stream sr = context.Request.InputStream;
            string filename = context.Request.Params["filename"];
            ErrorManager.Instance.LogMessage("upload : " + filename);
            try
            {
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                //将当前数据流写入服务器端文件夹ClientBin下
                using (FileStream fs = File.Create(ServerUtils.GetLocalPath(@"Files\" + filename), 4096))
                {
                    while ((bytesRead = sr.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        //向文件中写信息
                        fs.Write(buffer, 0, bytesRead);
                    }
                }

                context.Response.ContentType = "text/plain";
                context.Response.Write("上传成功");
                ErrorManager.Instance.LogMessage("upload success : " + filename);
            }
            catch (Exception e)
            {
                ErrorManager.Instance.LogMessage("upload fail : " + filename);
                context.Response.ContentType = "text/plain";
                context.Response.Write("上传失败, 错误信息:" + e.Message);
            }
            finally
            {
                sr.Dispose();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
